package com.ai_daily.aitiantian.bean;

import android.util.Log;

import java.io.Serializable;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseBean implements Serializable {

    public static String KEY = "@aitiantian";

    public static String SECRET = "OGM4ZjA1ZmE4YZSA4RTcxMDlkMDUyYmI5YmU3Yzk3NzM=";
    private String timestamp;
    private String verify = "true";

    private String sign;

    private String androidId;

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String isVerify() {
        return verify;
    }

    public void setVerify(String verify) {
        this.verify = verify;
    }

    public String getAndroidId() {
        return androidId;
    }

    public void setAndroidId(String androidId) {
        this.androidId = androidId;
    }

    @Override
    public String toString() {
        return "BaseBean{" +
                "timestamp='" + timestamp + '\'' +
                ", verify='" + verify + '\'' +
                ", androidId='" + androidId + '\'' +
                '}';
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    protected abstract Map<String,String> getParamsMap();

    public void sign() throws Exception{
        //业务参数map
        Map<String, String> params = getParamsMap();
        //当前时间戳
        params.put("timestamp", timestamp);
        params.put("androidId", androidId);
        params.put("verify", verify);
        //对参数先进行字典排序，再生成字符串
        StringBuilder sb = new StringBuilder();
        List<String> paramList = new ArrayList<>(params.keySet());
        Collections.sort(paramList);
        for (String paramName : paramList) {
            String paramValue = params.get(paramName);
            sb.append(paramName).append(":").append(paramValue).append("|");
        }
        Log.d("MD5",sb.toString());
        Log.d("MD5",KEY+'#'+sb.toString()+'#'+SECRET);
        // 对字符串进行MD5加密
        String sign = MD5(KEY+'#'+sb.toString()+'#'+SECRET);
        System.out.println("生成的签名为：" + sign);
        this.sign = sign;

    }
}
